<template>
  <div class="permission-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>权限分配管理</h2>
      <p>为不同角色分配相应的操作权限</p>
    </div>

    <!-- 角色选择区域 -->
    <div class="role-section">
      <el-card class="role-card">
        <template #header>
          <div class="card-header">
            <span>选择角色</span>
          </div>
        </template>

        <el-select
            v-model="selectedRoleId"
            placeholder="请选择角色"
            @change="onRoleChange"
            style="width: 100%"
        >
          <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
          />
        </el-select>

        <div v-if="selectedRole" class="role-info">
          <p>当前选择：<strong>{{ selectedRole.roleName }}</strong></p>
          <p class="role-description">为该角色分配相应的操作权限</p>
        </div>
      </el-card>
    </div>

    <!-- 权限分配区域 -->
    <div class="permission-section">
      <el-card class="permission-card">
        <template #header>
          <div class="card-header">
            <span>权限分配</span>
            <div class="header-actions">
              <el-button
                  type="primary"
                  :loading="loading.save"
                  @click="savePermissions"
                  :disabled="!selectedRoleId"
              >
                {{ loading.save ? '保存中...' : '保存权限' }}
              </el-button>
              <el-button @click="selectAll">全选</el-button>
              <el-button @click="clearAll">清空</el-button>
            </div>
          </div>
        </template>

        <!-- 权限树 -->
        <div v-loading="loading.permissions" class="permission-tree">
          <div
              v-for="(permissions, moduleName) in groupedPermissions"
              :key="moduleName"
              class="permission-module"
          >
            <h3 class="module-title">{{ moduleName }}</h3>
            <div class="permission-list">
              <!-- 使用 el-checkbox-group 包装多个 checkbox -->
              <el-checkbox-group v-model="selectedPermissionIds">
                <el-checkbox
                    v-for="permission in permissions"
                    :key="permission.id"
                    :label="permission.id"
                    class="permission-item"
                >
                  <div class="permission-info">
                    <span class="permission-name">{{ permission.permName }}</span>
                    <el-tag size="small" class="permission-code">
                      {{ permission.permCode }}
                    </el-tag>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>

          <div v-if="!hasPermissions" class="empty-state">
            <el-empty description="暂无权限数据" />
          </div>
        </div>

        <!-- 统计信息 -->
        <div v-if="hasPermissions" class="permission-stats">
          <el-divider />
          <div class="stats-info">
            <span>已选择 <strong>{{ selectedPermissionIds.length }}</strong> 个权限</span>
            <span>共 <strong>{{ totalPermissions }}</strong> 个权限</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllPermissions,
  getRolePermissions,
  assignPermissions
} from '../api/permissionApi.js'

export default {
  name: 'PermissionManagement',
  data() {
    return {
      // 角色相关
      roleList: [
        { id: 1, roleName: '院长' },
        { id: 2, roleName: '门诊医生' },
        { id: 3, roleName: '住院医生' },
        { id: 4, roleName: '住院前台护士' },
        { id: 5, roleName: '住院护理护士' },
        { id: 6, roleName: '资源管理人员' },
        { id: 7, roleName: '药师' },
        { id: 8, roleName: '人事职员' }
      ],
      selectedRoleId: null,

      // 权限相关
      groupedPermissions: {},
      selectedPermissionIds: [],

      // 加载状态
      loading: {
        permissions: false,
        save: false
      }
    }
  },
  computed: {
    // 当前选中的角色
    selectedRole() {
      return this.roleList.find(role => role.id === this.selectedRoleId) || null
    },

    // 是否有权限数据
    hasPermissions() {
      return Object.keys(this.groupedPermissions).length > 0
    },

    // 总权限数量
    totalPermissions() {
      let count = 0
      for (const module in this.groupedPermissions) {
        count += this.groupedPermissions[module].length
      }
      return count
    }
  },
  mounted() {
    // 页面加载时获取所有权限
    this.loadAllPermissions()
  },
  methods: {
    // 加载所有权限
    async loadAllPermissions() {
      this.loading.permissions = true
      try {
        const response = await getAllPermissions()
        if (response.data.code === 200) {
          this.groupedPermissions = response.data.obj || {}
          ElMessage.success('加载成功')
        } else {
          ElMessage.error(response.data.msg || '加载权限列表失败')
        }
      } catch (error) {
        console.error('加载权限列表失败:', error)
        ElMessage.error('加载权限列表失败')
      } finally {
        this.loading.permissions = false
      }
    },

    // 角色变更事件
    async onRoleChange(roleId) {
      if (!roleId) {
        this.selectedPermissionIds = []
        return
      }

      try {
        const response = await getRolePermissions(roleId)
        if (response.data.code === 200) {
          this.selectedPermissionIds = response.data.obj || []
          ElMessage.success(`已加载 ${this.selectedRole.roleName} 的权限`)
        } else {
          ElMessage.error(response.data.msg || '加载角色权限失败')
          this.selectedPermissionIds = []
        }
      } catch (error) {
        console.error('加载角色权限失败:', error)
        ElMessage.error('加载角色权限失败')
        this.selectedPermissionIds = []
      }
    },

    // 保存权限
    async savePermissions() {
      if (!this.selectedRoleId) {
        ElMessage.warning('请先选择角色')
        return
      }

      try {
        // 确认对话框
        await ElMessageBox.confirm(
            `确定要为【${this.selectedRole.roleName}】分配 ${this.selectedPermissionIds.length} 个权限吗？`,
            '确认保存',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        this.loading.save = true

        const data = {
          roleId: this.selectedRoleId,
          permissionIds: this.selectedPermissionIds
        }

        const response = await assignPermissions(data)

        if (response.data.code === 200) {
          ElMessage.success('权限分配成功')
        } else {
          ElMessage.error(response.data.msg || '权限分配失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('保存权限失败:', error)
          ElMessage.error('保存权限失败')
        }
      } finally {
        this.loading.save = false
      }
    },

    // 全选所有权限
    selectAll() {
      if (!this.hasPermissions) {
        ElMessage.warning('暂无权限数据')
        return
      }

      this.selectedPermissionIds = []
      for (const module in this.groupedPermissions) {
        this.groupedPermissions[module].forEach(permission => {
          this.selectedPermissionIds.push(permission.id)
        })
      }

      ElMessage.info(`已选择全部 ${this.selectedPermissionIds.length} 个权限`)
    },

    // 清空所有选择
    clearAll() {
      this.selectedPermissionIds = []
      ElMessage.info('已清空所有权限选择')
    }
  }
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.role-section {
  margin-bottom: 20px;
}

.role-info {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.role-info p {
  margin: 4px 0;
  font-size: 14px;
}

.role-description {
  color: #909399;
  font-size: 12px !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.permission-tree {
  min-height: 400px;
}

.permission-module {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.module-title {
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
  color: #409eff;
  font-size: 16px;
}

.permission-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
}

.permission-item {
  width: 100%;
  margin: 0;
}

.permission-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.permission-name {
  flex: 1;
  font-size: 14px;
}

.permission-code {
  font-family: 'Courier New', monospace;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.permission-stats {
  margin-top: 16px;
}

.stats-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-management {
    padding: 12px;
  }

  .permission-list {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>